package com.chenl.consumer.Logger;

import org.springframework.util.CollectionUtils;
import org.springframework.util.ObjectUtils;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;

public class LogThreadLocal {
    private static final ThreadLocal<LogVo> LOG_THREAD_LOCAL = new ThreadLocal<>();
    private static final ThreadLocal<String> LOGUTI_THREAD_LOCAL = new ThreadLocal<>();

    /**
     * 设置当前线程中的用户
     *
     * @param
     */
    public static void log(String log) {
        String uri = getURI();
        LogVo logg = get();
        if (!ObjectUtils.isEmpty(logg)) {
            List<LogEntity> list = logg.getList();
            LogEntity logEntity = list.get(list.size() - 1);//最后一个元素
            if (!logEntity.getClazz().equals(getClazzName() + "_" + getMethodName()+"()")) {
                LogEntity logVo = new LogEntity();
                logVo.setNumber(new AtomicInteger(logEntity.getNumber()).addAndGet(1));
                logVo.setLogType("NORMAL");
                logVo.setURI(uri);
                logVo.setClazz(getClazzName() + "_" + getMethodName()+"()");
                List<String> logContent = new ArrayList<>();
                logContent.add(log);
                logVo.setLogContent(logContent);
                list.add(logVo);
            } else {
                List<String> logContent = logEntity.getLogContent();
                logContent.add(log);
            }
        } else {
            List<LogEntity> list = new ArrayList<>();
            List<String> logContent = new ArrayList<>();
            LogEntity logEntity = new LogEntity();
            logEntity.setNumber(new AtomicInteger(1).get());
            logEntity.setClazz(getClazzName() + "_" + getMethodName()+"()");
            logEntity.setLogType("NORMAL");
            logEntity.setURI(uri);
            logContent.add(log);
            logEntity.setLogContent(logContent);
            list.add(logEntity);
            LogVo logVo=new LogVo();
            logVo.setList(list);
            LOG_THREAD_LOCAL.set(logVo);
        }
    }


    public static LogVo get() {
        return LOG_THREAD_LOCAL.get();
    }

    public static void set(LogVo logVo) {
        LOG_THREAD_LOCAL.set(logVo);
    }
    public static String getURI() {
        return LOGUTI_THREAD_LOCAL.get();
    }

    public static void setURI(String URI) {
        LOGUTI_THREAD_LOCAL.set(URI);
    }

    private static String getMethodName() {
        return Thread.currentThread().getStackTrace()[3].getMethodName();
    }

    private static String getClazzName() {
        return Thread.currentThread().getStackTrace()[3].getClassName();
    }

}
